<?php
// +----------------------------------------------------------------------
// | Iecms [ Make the most exquisite CMS ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009~2019 http://www.iemoo.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: iemoo <i@iemoo.com>
// +----------------------------------------------------------------------
// | DateTime: 2019/11/19 11:08
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\common\model\Page as PageModel;
use app\common\model\PageFiles as PageFilesModel;

use app\admin\validate\Page as PageValidate;
use think\exception\ValidateException;

use think\facade\Request;
use think\facade\View;
use think\facade\Config;

/**
 * 单页管理
 * Class AdminUser
 * @package app\admin\controller
 */
class Page extends Base
{
 
    /**
     * 单页管理
     * @return mixed
     */
    public function index()
    {
		$page_list = PageModel::order('sort desc,id desc')->paginate(10);
		View::assign('list',$page_list);

		return View::fetch('index');
    }



    /**
     * 添加单页
     * @return mixed
     */
    public function add()
    {

		if (Request::isPost()) {

			$data = Request::only([ 'title', 'name', 'images', 'keywords', 'description', 'content', 'template', 'hits', 'sort', 'status']);

            try {
				validate(PageValidate::class)->check($data);
			} catch (ValidateException $e) {
				// 验证失败 输出错误信息
				$this->error($e->getError());
			}
			
			$archives = PageModel::create($data);
			if (!$archives->isEmpty()) {
				//更新文件
				if(isset($data['images']) && is_array($data['images'])){
					//如果有差集，说明有新的文件
					if(!empty($data['images'])){						
						foreach($data['images']['id'] as $key => $val){
							$page_files = new PageFilesModel;
							$page_files->page_id = $archives->id;
							$page_files->files_id = $val;
							$page_files->name = $data['images']['name'][$key];
							$page_files->title = $data['images']['title'][$key];
							$page_files->sort = $key;
							$page_files->save();
						}
					}

				}
				$this->success('保存成功',url('admin/Page/index'));
			} else {
				$this->error('保存失败');
			}

        }

		//获取所有模版
        $template_list = get_template();
		View::assign('template_list',$template_list);

		return View::fetch('add');
    }


    /**
     * 编辑单页
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {

		if (Request::isPost()) {

			$data = Request::only(['id', 'title', 'name', 'images', 'keywords', 'description', 'content', 'template', 'hits', 'sort', 'status']);

			if(isset($data['images']) && is_array($data['images'])){

				//已有文件的ID
				$uploads_ids = PageFilesModel::where('page_id',$id)->column('files_id');
				//获取差集
				$diff_new = array_diff($data['images']['id'], $uploads_ids);	
				//获取差集
				$diff_old = array_diff($uploads_ids, $data['images']['id']);	

				//如果有差集，说明有新的文件
				if(!empty($diff_new)){
					foreach($diff_new as $key => $val){
						$page_files = new PageFilesModel;
						$page_files->page_id = $id;
						$page_files->files_id = $val;
						$page_files->name = $data['images']['name'][$key];
						$page_files->title = $data['images']['title'][$key];
						$page_files->save();
					}
				}

				//如果有差集，说明有要删除的文件
				if(!empty($diff_old)){
					foreach($diff_old as $key => $val){						
						PageFilesModel::where('page_id',$id)->where('files_id',$val)->delete();					
					}
				}

				//更新图片标题
				foreach($data['images']['id'] as $key => $val){	
					$fiels_updata = PageFilesModel::where('page_id',$id)->where('files_id',$val)->find();	
					$fiels_updata->title = $data['images']['title'][$key];
					$fiels_updata->sort = $key;
					$fiels_updata->save();									
				}


			}else{
				//也可能是要把图片都删除完
				PageFilesModel::where('page_id',$id)->delete();	
			}

            try {
				validate(PageValidate::class)->check($data);
			} catch (ValidateException $e) {
				// 验证失败 输出错误信息
				$this->error($e->getError());
			}

			if (PageModel::update($data, ['id' => $id])) {
				$this->success('更新成功');
			} else {
				$this->error('更新失败');
			}

        }


        $page = PageModel::find($id);		
		$images = $page->files->toArray();		
		//获取所有模版
        $template_list = get_template();
		View::assign('template_list',$template_list);

		View::assign('info',$page);
		View::assign('images',$images);

		return View::fetch('edit');
    }

    /**
     * 删除内容
     * @param $id
     */
    public function delete($id)
    {
        if (PageModel::destroy($id)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
}